package com.usian.controller;

import com.usian.config.TestConfig;
import com.usian.config.UserConfig;
import com.usian.pojo.User;
import com.usian.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    private static  final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserConfig userConfig;

    @Autowired
    TestConfig testConfig;

    @Autowired
    private UserService userService;

    @GetMapping("/index")
    @ResponseBody
    public String index(){
        return "我的第一 frist springboot project  2343432423%￥￥￥";
    }

    /**
     * 查询所有
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model){
        List<User> userList = userService.findAll();
        model.addAttribute("userList",userList);

        LOGGER.debug("222222222222");
        System.out.println("6666666666666");
        return "list";
    }

    /**
     * 跳转到新增页面
     * @return
     */
    @RequestMapping("/toAdd")
    public String  toAdd(){
        return "add";
    }

    /**
     * 跳转到修改页面
     * @return
     */
    @RequestMapping("/toUpdate")
    public String  toUpdate(Integer userId ,Model model){
        User user = userService.findById(userId);
        model.addAttribute("user",user);
        return "update";
    }

    /**
     * 保存用户
     *
     * @param user
     * @return
     */
    @RequestMapping("/addUser")
    public String insertUser(User user){
        if(user!=null && user.getUserId()!=null){
            userService.updateUser(user);
        }else{
            userService.insertUser(user);
        }
        return "redirect:/user/findAll";
    }


    /**
     * 删除
     *
     * @param userId
     * @return
     */
    @RequestMapping("/toDelete")
    public String toDelete(Integer userId){
        if(userId!=null){
            userService.delUser(userId);
            return "redirect:/user/findAll";
        }
        return "";
    }



    @RequestMapping("/findById/{id}")
    @ResponseBody
    public User findById(@PathVariable Integer id){
        return userService.findById(id);
    }

    @RequestMapping("/findByUserName/{name}/{password}")
    @ResponseBody
    public List<User> findByUserName(@PathVariable String name, @PathVariable String password){
        return userService.findByUserName(name,password);
    }




}
